﻿using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;

using Unity.Transforms;
using Unity.Burst;
using UnityEngine;
using Unity.Mathematics;

[DisableAutoCreation]
public partial struct EnemySpawnerSystem : ISystem
{
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<EnemySpawner>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        state.Enabled = false; //只执行一次

        //可以直接使用EntityManager or EntityCommandBuffer
        EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);
        EnemySpawner enemySpawner = SystemAPI.GetSingleton<EnemySpawner>(); //获取单例


        for (int i = 0; i < enemySpawner.MaxCount; i++)
        {
            var x = UnityEngine.Random.Range(-20f, 20f);
            var y = UnityEngine.Random.Range(-20f, 20f);

            Entity entity = ecb.Instantiate(enemySpawner.preFab);
            ecb.SetComponent(entity, new LocalTransform
            {
                Position = new float3(x, y, 0),
                Rotation = quaternion.identity,
                Scale = 1f
            });
            ecb.AddComponent(entity, new HealthComp() { value = 3 });
            //ecb.AddComponent<SortInQuadTreeComp>(entity);
        }
        ecb.Playback(state.EntityManager);
    }
}


